import {
  cooperationBehavior
} from "../../../../behaviors/cooperation.js";
import {
  userInfoBehavior
} from "../../../../behaviors/userInfo.js";
import constant from "../../../../common/constant.js";
const config = require("../../../../utils/config.js");
var app = getApp();
/** gio埋点 */
const _map = {
  NEWHOUSE: constant.XIN_FANG,
  RENT: constant.CHU_ZU,
  SALES: constant.ER_SHOU,
};
Page({
  behaviors: [cooperationBehavior, userInfoBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    isVmShow: false, //虚拟电话弹层
    currentSwiper: 0, //轮播图当前位置
    corporateHousing: ["专人核验", "品质保障"],
    tagList: [],
    isShowdajiaPng: true, //判断打假按钮是否显示
    showMap: false, //默认不展示地图
    loadSeccess: false, //展示房源信息不存在的状态
    tabList: config.tabList,
    houseTime: '',
    cooperationId: '',
    phoneCooperationId: '', //拨打虚拟号需要的CooperationId
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showShareMenu({
      withShareTicket: true,
    });
    app.globalData.loginPromise.then(() => {
      app.mobileLogin(false, '', false)
        .then(() => {
          this.setData({
            cooperationId: options.cooperationId
          });
          this.getHouseInfo();
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({
              url: "/pages/house/RentalHouseDetail/coopertionHouseInfo/coopertionHouseInfo?cooperationId=" + options.cooperationId
            });
          };
        })
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getHouseInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let sessionUser = getApp().globalData.sessionUser;
    let agentId = sessionUser.id;
    const {
      detailContent,
      cooperationId
    } = this.data
    const {
      houImageVO,
      houDelVO
    } = detailContent || {}
    let buildSize = houDelVO.buildSize ? houDelVO.buildSize + '㎡' : '';
    let price = houDelVO.delegationType === "SALES" ? `${houDelVO.totalPrices ? houDelVO.totalPrices / 10000 : 0}` : `${houDelVO.totalPrices || 0}`
    let unit = houDelVO.delegationType === "SALES" ? '万' : '元/月'
    let result = {
      title: houDelVO.title ? houDelVO.title : `${houDelVO.resblockName || ''} ${houDelVO.room || 0}室${houDelVO.hall || 0}厅 ${buildSize} ${price ? price + unit : ''}`,
      path: `/pages/house/RentalHouseDetail/teamworkHouseDetail/teamworkHouseDetail?cooperationId=${cooperationId}&agentId=${agentId}`,
      imageUrl: houImageVO && houImageVO.length ? houImageVO[0].url : '',
    }
    return result
  },
  //获取房源详情
  getHouseInfo() {
    const that = this,
      bannerList = [];
    wx.showLoading({
      title: '加载中...',
    })
    this.getInfoByCooperationId(that.data.cooperationId, true).then((content) => {
      this.checkCooperationStatus(content.hmCooperationDelVO.cooperationDown)
      content.houDelVO = content.hmCooperationDelVO;
      content.houDelVO.id = content.houDelVO.delId;
      wx.gio("setPage", {
        [constant.ROOM_TYPE_PVAR]: _map[content.houDelVO.delegationType],
      });
      for (var k in content.houImageVO) {
        bannerList.push(content.houImageVO[k].url);
      }
      that.setData({
        markers: [{
          id: 0,
          latitude: content.houDelVO.lat,
          longitude: content.houDelVO.lng,
          title: content.houDelVO.addr,
          callout: {
            content: content.houDelVO.addr,
            display: 'ALWAYS',
            padding: 8,
            bgColor: '#fff',
            fontSize: '24rpx',
            color: '#333333',
          },
        }, ],
        bannerList,
        loadSeccess:true,
        detailContent: content,
        jjrVO: this.formatAuthenticatedInfo(content.jjrVO),
        hmCooperatioonNearByInfoVO: content.hmCooperatioonNearByInfoVO, //附近可合作
        hmCooperation: content.hmCooperationAuthenticityCheck, //数据检测
      })
      // 自己拼接tagListTmp数据
      let tagListTmp = []
      let hmCooperationDelVO = this.data.detailContent.hmCooperationDelVO
      let direction = hmCooperationDelVO.direction //朝向
      let buildNumNew = hmCooperationDelVO.buildNumNew //楼层
      let floorHeight = hmCooperationDelVO.floorHeight //楼高
      let houYears = hmCooperationDelVO.houYears //满五
      let unique = hmCooperationDelVO.unique || '' // 是否唯一  2不唯一  1唯一
      if (unique && unique !== undefined && unique !== '') {
        if (unique == 2) {
          unique = '不唯一'
        } else {
          unique = '唯一'
        }
      }
      if (direction && direction !== '' && direction !== undefined) {
        direction = "朝向" + direction
        tagListTmp.push(direction)
      }
      if (floorHeight && floorHeight !== undefined && floorHeight !== '') {
        floorHeight = floorHeight + '楼'
        tagListTmp.push(floorHeight)
      } else {
        if (buildNumNew && buildNumNew !== undefined && buildNumNew !== '') {
          tagListTmp.push(buildNumNew)
        }
      }
      if (houYears && houYears !== undefined && houYears !== '') {
        houYears = houYears + unique
        tagListTmp.push(houYears)
      }
      this.setData({
        tagList: tagListTmp
      })
      //自己计算的更新时间
      let finalConfirmTime = content.houseCooperation.finalConfirmTime
      let houseInfoUpdateTime = content.houseCooperation.houseInfoUpdateTime
      let newTime = new Date().getTime()
      if (finalConfirmTime - houseInfoUpdateTime < 0) {
        let showTime = (newTime - houseInfoUpdateTime) / 86400000
        this.setData({
          houseTime: showTime
        })
      } else {
        let showTime = (newTime - finalConfirmTime) / 86400000
        this.setData({
          houseTime: showTime
        })
      }
      wx.hideLoading()
    })
  },
  //监听轮播的位置
  swiperChange(e) {
    const that = this,
      currentSwiper = e.detail.current;
    const tagName = that.data.detailContent.houImageVO[currentSwiper].tagName;
    this.setData({
      currentSwiper: currentSwiper,
      tagName: tagName,
    });
  },
  //预览轮播图
  previewBannerImage: function (e) {
    var bannerList = this.data.bannerList,
      current = bannerList[this.data.currentSwiper];
    wx.previewImage({
      current: current,
      urls: bannerList,
    });
  },
  // 是否下架
  checkCooperationStatus(status) {
    if (status) {
      wx.showModal({
        content: '该房源已下架~',
        showCancel: false,
      })
    }
  },
  // 打假的点击事件
  anti_counterfeit(e) {
    let userid = e.currentTarget.dataset.userid
    let houseid = e.currentTarget.dataset.houseid
    this.dialog = this.selectComponent("#com-counterfeity");
    this.dialog.showDialog()
    this.setData({
      useridTmp: userid,
      houseidTmp: houseid
    })
  },
  cancelEventX(e) {
    let visible = e.detail.visible
    if (visible) {
      this.setData({
        isShowdajiaPng: false
      })
    }
  },
  // 地图的点击事件
  handleNavigation() {
    const lat = this.data.detailContent.houDelVO.lat;
    const lng = this.data.detailContent.houDelVO.lng;
    wx.openLocation({
      latitude: Number(lat),
      longitude: Number(lng),
      scale: 16,
    });
  },
  goMapDetails(e) {
    const currentTitle = e.currentTarget.dataset.title;
    const currentTabState = e.currentTarget.dataset.index;
    const lat = this.data.detailContent.houDelVO.lat;
    const lng = this.data.detailContent.houDelVO.lng;
    this.setData({
      currentTabState,
    });
    wx.navigateTo({
      url: `/pages/house/RentalHouseDetail/mapDetails/mapDetails?latitude=${lat}&longitude=${lng}&currentTitle=${currentTitle}&currentTabState=${currentTabState}`,
    });
  },
  // 展开
  showMore() {
    this.setData({
      showMap: true
    })
  },
  // 关闭
  closeMore() {
    this.setData({
      showMap: false
    })
  },

  // 附近可合作的打电话
  gotoPhoneX(e) {
    let phoneCooperationId = e.detail.cooperationId
    this.setData({
      phoneCooperationId,
      isVmShow: true
    })
  },
  handleVmVisible(e) {
    this.setData({
      isVmShow: e.detail.visible,
    })
  },
  //查看头像
  lookPicture() {
    wx.gio("track", constant.LOOK_PICTURE, {
      [constant.HOUSE_INFO]: '查看头像',
    });
    let pictureUrls = []
    pictureUrls.push(this.data.jjrVO.avatar)
    wx.previewImage({
      urls: pictureUrls,
    })
  },
  //查看完整的个性宣言
  lookDeclaration() {
    wx.gio("track", constant.LOOK_DECLARATION, {
      [constant.HOUSE_INFO_DECLARATION]: '查看完整的个性宣言',
    });
    wx.showToast({
      title: this.data.jjrVO.declaration,
      icon: 'none',
      duration: 2000
    })
  },
  // 编辑按钮
  gotoEditHouseInfo() {
    //此cooperationId是在合作房源列表传递过来的   继续使用在编辑页面查询使用
    let cooperationId = this.data.cooperationId
    wx.navigateTo({
      url: '/pages/cooperation/editHouseInfo/editHouseInfo?cooperationId=' + cooperationId,
    })
  }
})